<?php
/*
 * class for   Creates a new model.
 * If creation is successful, the browser will be redirected to the 'view' page.
 * @author Chamara Bandara
 * @copyright Copyright &copy; 2011 Allion Technologies (Pvt) Ltd
 */

class CreateAction extends CAction {

   public function run() {
      $controller = $this->getController();
      $model = new User;

      if (isset($_POST['User'])) {

         $model->attributes = $_POST['User'];
         if ($model->password)
            $model->password = User::model()->encryptPassword($_POST['User']['password']);
         $model->status = "Inactive";
         if (!$model->save()) {
            
         } else {
            $id = $model->getPrimaryKey();
            $paths = $model->createImageDirectories($id);
            $modelPicture = CUploadedFile::getInstance($model, 'picture');

            if (isset($modelPicture) && !empty($modelPicture)) {
               $rand = md5($model->generateRandomString());
               $imageType = explode('image/', $modelPicture->getType());
               $file = Yii::app()->params['imageSavePath'] . $paths['thumbnail'] . DIRECTORY_SEPARATOR . $rand . '.' . $imageType[1];
               if ($modelPicture->saveAs($file))
                  $img = Yii::app()->simpleImage->load($file);
               $img->resizeToWidth(128);
               $img->save($file);
               $model->picture = $paths['thumbnail'] . DIRECTORY_SEPARATOR . $rand . '.' . $imageType[1];
               $model->save();
            }
            Yii::app()->user->setFlash('success', "User Created successfully!!");
            $controller->redirect(array('view', 'id' => $model->id));
         }
      }

      $controller->render('create', array(
          'model' => $model,
      ));
   }
}